package com.cskaoyan.converter;


import lombok.SneakyThrows;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Since 2022/12/29 14:08
 * @Author LA
 * @Description: 自定义转换器(自动使用)：实现 String 转指定格式 Date
 */
@Component
public class String2DateConverter implements Converter<String, Date> {
    @SneakyThrows
    @Override
    public Date convert(String source) {
        // 时间字符串为null或者为空串时
        if (source == null || "".equals(source)) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = null;
        if (source.length() == 19) {
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else {
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        }
        return simpleDateFormat.parse(source);
    }


}
